<template>
  <view class="container">

    <!-- 邀请卡片 -->
    <view class="invite-card">
      <view class="card-header">
        <text class="title">我的专属邀请码</text>
        <text  @click="refreshCode" :loading="refreshing">
          <u-icon name="reload" size="16"></u-icon>
          刷新
        </text>
      </view>
      
      <view class="invite-code" @click="copyInviteCode">
        <uqrcode ref="uqrcode" canvas-id="qrcode" :value="`https://shgw.hdkeji.cn/invite?code=${inviteInfo.my_invite_code}`" :options="{ margin: 10 }"></uqrcode>
        <u-icon name="cut" color="#2979ff" size="20"></u-icon>
      </view>
      
      <view class="invite-stats">
        <view class="stat-item">
          <text class="value">{{ inviteInfo.invite_count || 0 }}</text>
          <text class="label">成功邀请</text>
        </view>
        <view class="stat-item">
          <text class="value">{{ inviteInfo.invite_rewards || 0 }}</text>
          <text class="label">奖励</text>
        </view>
      </view>
    </view>
    
    <!-- 分享选项 -->
    <view class="share-options">
      <text class="section-title">分享邀请</text>
      <view class="option-list">
		<u-button type="primary" text="保存二维码" @click="saveQRCode"></u-button>
      </view>
    </view>
    
    <!-- 邀请规则 -->
    <view class="invite-rules">
      <text class="section-title">邀请规则</text>
      <view class="rules-content">
        <view class="rule-item">
          <u-icon name="checkmark-circle" color="#4caf50" size="16"></u-icon>
          <text>每成功邀请一位，您将获得一定积分奖励</text>
        </view>
        <view class="rule-item">
          <u-icon name="checkmark-circle" color="#4caf50" size="16"></u-icon>
          <text>每月邀请排行榜前10名有额外奖励</text>
        </view>
      </view>
    </view>
    
    <!-- 邀请列表 -->
    <view class="invite-list">
      <view class="list-header">
        <text class="section-title">邀请记录</text>
        <text class="total">共{{ inviteList.total }}人</text>
      </view>
      
      <view v-if="loading" class="loading">
        <text>加载中...</text>
      </view>
      
      <view v-else-if="inviteList.list.length === 0" class="no-data">
        <u-empty text="暂无邀请记录" mode="list"></u-empty>
      </view>
      
      <view v-else class="list-content">
        <view v-for="(item, index) in inviteList.list" :key="index" class="list-item">
          <view class="user-info">
            <u-avatar :text="item.name ? item.name.substring(0, 1) : ''" size="40"></u-avatar>
            <view class="user-detail">
              <text class="user-name">{{ item.name }}</text>
              <text class="user-department">{{ item.department && item.department.name }}</text>
            </view>
          </view>
          <view class="invite-time">
            {{ formatTime(item.create_time) }}
          </view>
        </view>
        
        <view v-if="hasMore" class="load-more">
          <u-button @click="loadMore" :loading="loadingMore" plain>
            加载更多
          </u-button>
        </view>
      </view>
    </view>
    
    <!-- 分享弹窗 -->
    <u-modal v-model="showShareModal" title="分享邀请" :show-confirm-button="false" :show-cancel-button="false">
      <view class="share-modal-content">
        <image :src="qrcodeUrl" mode="widthFix" class="qrcode-image"></image>
        <text class="share-tip">扫描二维码注册，自动填写您的邀请码</text>
        <view class="share-actions">
          <u-button @click="saveImage" type="primary">保存图片</u-button>
          <u-button @click="showShareModal = false">关闭</u-button>
        </view>
      </view>
    </u-modal>
  </view>
</template>

<script>
	import {
		store,
		mutations
	} from '@/uni_modules/uni-id-pages/common/store.js'
export default {
  data() {
    return {
      inviteInfo: {
        invite_code: '',
        invite_count: 0,
        invite_rewards: 0
      },
      inviteList: {
        list: [],
        total: 0,
        page: 1,
        limit: 10
      },
      loading: true,
      loadingMore: false,
      refreshing: false,
      showShareModal: false,
      qrcodeUrl: '',
      hasMore: true
    }
  },
  onLoad() {
    this.loadInviteData();
  },
  computed: {
  	userInfo() {
  		return store.userInfo
  	},
  	hasLogin(){
  		return store.hasLogin
  	}
  },
  methods: {
    // 加载邀请数据
    async loadInviteData() {
      this.loading = true;
      try {
        // 获取邀请信息
        const inviteRes = await uniCloud.callFunction({
          name: 'mydb-invite',
          data: {
            action: 'getInviteInfo'
          }
        });
        console.log('inviteRes',inviteRes)
        if (inviteRes.result.code === 200) {
          this.inviteInfo = inviteRes.result.data;
        }
        
        // 获取邀请列表
        await this.loadInviteList();
        
      } catch (err) {
        console.error('加载邀请数据失败:', err);
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        });
      }
      this.loading = false;
    },
    
    // 加载邀请列表
    async loadInviteList() {
      try {
        const res = await uniCloud.callFunction({
          name: 'mydb-invite',
          data: {
            action: 'getInviteList',
            data: {
              page: this.inviteList.page,
              limit: this.inviteList.limit
            }
          }
        });
        
        if (res.result.code === 200) {
          const data = res.result.data;
          if (this.inviteList.page === 1) {
            this.inviteList.list = data.list;
          } else {
            this.inviteList.list = [...this.inviteList.list, ...data.list];
          }
          
          this.inviteList.total = data.total;
          this.hasMore = this.inviteList.list.length < data.total;
        }
      } catch (err) {
        console.error('加载邀请列表失败:', err);
      }
    },
    
    // 加载更多
    async loadMore() {
      if (!this.hasMore || this.loadingMore) return;
      
      this.loadingMore = true;
      this.inviteList.page += 1;
      await this.loadInviteList();
      this.loadingMore = false;
    },
    
    // 刷新邀请码
    async refreshCode() {
      this.refreshing = true;
      try {
        // 获取邀请信息
        const inviteRes = await uniCloud.callFunction({
          name: 'mydb-invite',
          data: {
            action: 'getInviteInfo'
          }
        });
        
        if (inviteRes.result.code === 200) {
          this.inviteInfo = inviteRes.result.data;
          uni.showToast({
            title: '邀请码已刷新',
            icon: 'success'
          });
        }
      } catch (err) {
        console.error('刷新邀请码失败:', err);
        uni.showToast({
          title: '刷新失败',
          icon: 'none'
        });
      }
      this.refreshing = false;
    },
    
    // 复制邀请码
    copyInviteCode() {
      if (!this.inviteInfo.my_invite_code) return;
      
      uni.setClipboardData({
        data: this.inviteInfo.my_invite_code,
        success: () => {
          uni.showToast({
            title: '邀请码已复制',
            icon: 'success'
          });
        }
      });
    },
    
    // 获取应用基础URL
    getAppBaseUrl() {
      // 这里应该是你的应用下载页或注册页地址
      return 'https://your-app-domain.com/download';
    },
    // 生成二维码
    generateQRCode() {
      // 这里应该调用二维码生成API
      // 简化实现，使用一个示例二维码图片
      this.qrcodeUrl = 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=' + 
        encodeURIComponent(`${this.getAppBaseUrl()}?invite_code=${this.inviteInfo.my_invite_code}`);
    },
    
    // 保存二维码
    saveQRCode() {
      this.$refs.uqrcode.save({
        success: () => {
          uni.showToast({
            icon: 'success',
            title: '保存成功'
          });
        }
      });
    },
    
    // 保存图片
    saveImage() {
      uni.showLoading({
        title: '保存中...'
      });
      
      uni.downloadFile({
        url: this.qrcodeUrl,
        success: (res) => {
          if (res.statusCode === 200) {
            uni.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success: () => {
                uni.hideLoading();
                uni.showToast({
                  title: '保存成功',
                  icon: 'success'
                });
                this.showShareModal = false;
              },
              fail: () => {
                uni.hideLoading();
                uni.showToast({
                  title: '保存失败',
                  icon: 'none'
                });
              }
            });
          }
        },
        fail: () => {
          uni.hideLoading();
          uni.showToast({
            title: '下载失败',
            icon: 'none'
          });
        }
      });
    },
    
    // 格式化时间
    formatTime(timestamp) {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  padding: 20rpx;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.invite-card {
  background: linear-gradient(135deg, #2979ff, #2962ff);
  border-radius: 16rpx;
  padding: 30rpx;
  color: white;
  margin-bottom: 30rpx;
  box-shadow: 0 10rpx 20rpx rgba(41, 121, 255, 0.2);
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
    
    .title {
      font-size: 32rpx;
      font-weight: bold;
    }
  }
  
  .invite-code {
    display: flex;
    justify-content: center;
    align-items: center;
    background: rgba(255, 255, 255, 0.2);
    border-radius: 12rpx;
    padding: 20rpx;
    margin-bottom: 30rpx;
    
    .code {
      font-size: 48rpx;
      font-weight: bold;
      letter-spacing: 4rpx;
      margin-right: 20rpx;
    }
  }
  
  .invite-stats {
    display: flex;
    justify-content: space-around;
    
    .stat-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      
      .value {
        font-size: 40rpx;
        font-weight: bold;
        margin-bottom: 10rpx;
      }
      
      .label {
        font-size: 26rpx;
        opacity: 0.8;
      }
    }
  }
}

.share-options, .invite-rules, .invite-list {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 10rpx 20rpx rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 30rpx;
  display: block;
}

.option-list {
  display: flex;
  justify-content: space-around;
  
  .option-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .option-icon {
      width: 80rpx;
      height: 80rpx;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 15rpx;
      
      &.wechat {
        background-color: #07C160;
      }
      
      &.moment {
        background-color: #7BB32E;
      }
      
      &.qrcode {
        background-color: #2979ff;
      }
      
      &.link {
        background-color: #FF976A;
      }
    }
    
    .option-text {
      font-size: 26rpx;
      color: #666;
    }
  }
}

.rules-content {
  .rule-item {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    text {
      margin-left: 15rpx;
      font-size: 28rpx;
      color: #666;
    }
  }
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
  
  .total {
    font-size: 26rpx;
    color: #999;
  }
}

.loading, .no-data {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60rpx 0;
  
  text {
    margin-top: 20rpx;
    color: #999;
  }
}

.list-content {
  .list-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 25rpx 0;
    border-bottom: 1rpx solid #f1f1f1;
    
    &:last-child {
      border-bottom: none;
    }
    
    .user-info {
      display: flex;
      align-items: center;
      
      .user-detail {
        margin-left: 20rpx;
        display: flex;
        flex-direction: column;
        
        .user-name {
          font-size: 32rpx;
          font-weight: 500;
          margin-bottom: 5rpx;
        }
        
        .user-department {
          font-size: 26rpx;
          color: #999;
        }
      }
    }
    
    .invite-time {
      font-size: 26rpx;
      color: #999;
    }
  }
  
  .load-more {
    padding: 30rpx 0;
    display: flex;
    justify-content: center;
  }
}

.share-modal-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 30rpx;
  
  .qrcode-image {
    width: 300rpx;
    height: 300rpx;
    margin-bottom: 30rpx;
  }
  
  .share-tip {
    font-size: 28rpx;
    color: #666;
    margin-bottom: 30rpx;
    text-align: center;
  }
  
  .share-actions {
    width: 100%;
    
    button {
      margin-bottom: 20rpx;
      
      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}
</style>